﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;

namespace Admin.NET.Application;

/// <summary>
/// 入库管理服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class NboundmanagementService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Nboundmanagement> _nboundmanagementRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public NboundmanagementService(SqlSugarRepository<Nboundmanagement> nboundmanagementRep, ISqlSugarClient sqlSugarClient)
    {
        _nboundmanagementRep = nboundmanagementRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询入库管理 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询入库管理")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<NboundmanagementOutput>> Page(PageNboundmanagementInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _nboundmanagementRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.InboundOrderNumber.Contains(input.Keyword) || u.Buddies.Contains(input.Keyword) || u.Contact.Contains(input.Keyword) || u.Remark.Contains(input.Keyword) || u.InboundDetails.Contains(input.Keyword) || u.UploadAttachments.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.InboundOrderNumber), u => u.InboundOrderNumber.Contains(input.InboundOrderNumber.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Buddies), u => u.Buddies.Contains(input.Buddies.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Contact), u => u.Contact.Contains(input.Contact.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Remark), u => u.Remark.Contains(input.Remark.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.InboundDetails), u => u.InboundDetails.Contains(input.InboundDetails.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.UploadAttachments), u => u.UploadAttachments.Contains(input.UploadAttachments.Trim()))
            .WhereIF(input.InboundType != null, u => u.InboundType == input.InboundType)
            .WhereIF(input.RepositoryName != null, u => u.RepositoryName == input.RepositoryName)
            .WhereIF(input.InboundDateRange?.Length == 2, u => u.InboundDate >= input.InboundDateRange[0] && u.InboundDate <= input.InboundDateRange[1])
            .WhereIF(input.AssociatedTrackingNumber != null, u => u.AssociatedTrackingNumber == input.AssociatedTrackingNumber)
            .WhereIF(input.vendorId != null, u => u.vendorId == input.vendorId)
            .WhereIF(input.Attn != null, u => u.Attn == input.Attn)
            .WhereIF(input.DocumentStatus != null, u => u.DocumentStatus == input.DocumentStatus)
            .WhereIF(input.InboundQuantity != null, u => u.InboundQuantity == input.InboundQuantity)
            .WhereIF(input.Reviewers != null, u => u.Reviewers == input.Reviewers)
            .LeftJoin<Inboundtype>((u, inboundType) => u.InboundType == inboundType.Id)
            .LeftJoin<Warehouse>((u, inboundType, repositoryName) => u.RepositoryName == repositoryName.Id)
            .LeftJoin<Commodityinformation>((u, inboundType, repositoryName, associatedTrackingNumber) => u.AssociatedTrackingNumber == associatedTrackingNumber.Id)
            .LeftJoin<Vendor>((u, inboundType, repositoryName, associatedTrackingNumber, vendor) => u.vendorId == vendor.Id)
            .LeftJoin<UserManagement>((u, inboundType, repositoryName, associatedTrackingNumber, vendor, attn) => u.Attn == attn.Id)
            .Select((u, inboundType, repositoryName, associatedTrackingNumber, vendor, attn) => new NboundmanagementOutput
            {
                Id = u.Id,
                InboundOrderNumber = u.InboundOrderNumber,
                InboundType = u.InboundType,
                InboundTypeFkDisplayName = $"{inboundType.InboundTypeName}",
                RepositoryName = u.RepositoryName,
                RepositoryNameFkDisplayName = $"{repositoryName.WarehouseName}",
                InboundDate = u.InboundDate,
                AssociatedTrackingNumber = u.AssociatedTrackingNumber,
                AssociatedTrackingNumberFkDisplayName = $"{associatedTrackingNumber.ItemName}",
                vendorId = u.vendorId,
                vendorFkDisplayName = $"{vendor.VendorName}",
                Buddies = u.Buddies,
                Contact = u.Contact,
                Attn = u.Attn,
                AttnFkDisplayName = $"{attn.UserName}",
                Remark = u.Remark,
                InboundDetails = u.InboundDetails,
                UploadAttachments = u.UploadAttachments,
                DocumentStatus = u.DocumentStatus,
                InboundQuantity = u.InboundQuantity,
                InboundAmount = u.InboundAmount,
                Reviewers = u.Reviewers,
                IsDelete = u.IsDelete,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取入库管理详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取入库管理详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Nboundmanagement> Detail([FromQuery] QueryByIdNboundmanagementInput input)
    {
        return await _nboundmanagementRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加入库管理 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加入库管理")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddNboundmanagementInput input)
    {
        var entity = input.Adapt<Nboundmanagement>();
        return await _nboundmanagementRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新入库管理 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新入库管理")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateNboundmanagementInput input)
    {
        var entity = input.Adapt<Nboundmanagement>();
        await _nboundmanagementRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除入库管理 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除入库管理")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteNboundmanagementInput input)
    {
        var entity = await _nboundmanagementRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _nboundmanagementRep.FakeDeleteAsync(entity);   //假删除
        //await _nboundmanagementRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除入库管理 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除入库管理")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteNboundmanagementInput> input)
    {
        var exp = Expressionable.Create<Nboundmanagement>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _nboundmanagementRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _nboundmanagementRep.FakeDeleteAsync(list);   //假删除
        //return await _nboundmanagementRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataNboundmanagementInput input)
    {
        var inboundTypeData = await _nboundmanagementRep.Context.Queryable<Inboundtype>()
            .InnerJoinIF<Nboundmanagement>(input.FromPage, (u, r) => u.Id == r.InboundType)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.InboundTypeName}"
            }).ToListAsync();
        var repositoryNameData = await _nboundmanagementRep.Context.Queryable<Warehouse>()
            .InnerJoinIF<Nboundmanagement>(input.FromPage, (u, r) => u.Id == r.RepositoryName)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.WarehouseName}"
            }).ToListAsync();
        var associatedTrackingNumberData = await _nboundmanagementRep.Context.Queryable<Commodityinformation>()
            .InnerJoinIF<Nboundmanagement>(input.FromPage, (u, r) => u.Id == r.AssociatedTrackingNumber)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.ItemName}"
            }).ToListAsync();
        var vendorIdData = await _nboundmanagementRep.Context.Queryable<Vendor>()
            .InnerJoinIF<Nboundmanagement>(input.FromPage, (u, r) => u.Id == r.vendorId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.VendorName}"
            }).ToListAsync();
        var attnData = await _nboundmanagementRep.Context.Queryable<UserManagement>()
            .InnerJoinIF<Nboundmanagement>(input.FromPage, (u, r) => u.Id == r.Attn)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.UserName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "inboundType", inboundTypeData },
            { "repositoryName", repositoryNameData },
            { "associatedTrackingNumber", associatedTrackingNumberData },
            { "vendorId", vendorIdData },
            { "attn", attnData },
        };
    }
    
    /// <summary>
    /// 导出入库管理记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出入库管理记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageNboundmanagementInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportNboundmanagementOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "入库管理导出记录");
    }
    
    /// <summary>
    /// 下载入库管理数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载入库管理数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportNboundmanagementOutput>(), "入库管理导入模板", (_, info) =>
        {
            if (nameof(ExportNboundmanagementOutput.InboundTypeFkDisplayName) == info.Name) return _nboundmanagementRep.Context.Queryable<Inboundtype>().Select(u => $"{u.InboundTypeName}").Distinct().ToList();
            if (nameof(ExportNboundmanagementOutput.RepositoryNameFkDisplayName) == info.Name) return _nboundmanagementRep.Context.Queryable<Warehouse>().Select(u => $"{u.WarehouseName}").Distinct().ToList();
            if (nameof(ExportNboundmanagementOutput.AssociatedTrackingNumberFkDisplayName) == info.Name) return _nboundmanagementRep.Context.Queryable<Commodityinformation>().Select(u => $"{u.ItemName}").Distinct().ToList();
            if (nameof(ExportNboundmanagementOutput.vendorFkDisplayName) == info.Name) return _nboundmanagementRep.Context.Queryable<Vendor>().Select(u => $"{u.VendorName}").Distinct().ToList();
            if (nameof(ExportNboundmanagementOutput.AttnFkDisplayName) == info.Name) return _nboundmanagementRep.Context.Queryable<UserManagement>().Select(u => $"{u.UserName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入入库管理记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入入库管理记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportNboundmanagementInput, Nboundmanagement>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 入库类型
                    var inboundTypeLabelList = pageItems.Where(x => x.InboundTypeFkDisplayName != null).Select(x => x.InboundTypeFkDisplayName).Distinct().ToList();
                    if (inboundTypeLabelList.Any()) {
                        var inboundTypeLinkMap = _nboundmanagementRep.Context.Queryable<Inboundtype>().Where(u => inboundTypeLabelList.Contains($"{u.InboundTypeName}")).ToList().ToDictionary(u => $"{u.InboundTypeName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.InboundType = inboundTypeLinkMap.GetValueOrDefault(e.InboundTypeFkDisplayName ?? "");
                            if (e.InboundType == null) e.Error = "入库类型链接失败";
                        });
                    }
                    // 链接 仓库名称
                    var repositoryNameLabelList = pageItems.Where(x => x.RepositoryNameFkDisplayName != null).Select(x => x.RepositoryNameFkDisplayName).Distinct().ToList();
                    if (repositoryNameLabelList.Any()) {
                        var repositoryNameLinkMap = _nboundmanagementRep.Context.Queryable<Warehouse>().Where(u => repositoryNameLabelList.Contains($"{u.WarehouseName}")).ToList().ToDictionary(u => $"{u.WarehouseName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.RepositoryName = repositoryNameLinkMap.GetValueOrDefault(e.RepositoryNameFkDisplayName ?? "");
                            if (e.RepositoryName == null) e.Error = "仓库名称链接失败";
                        });
                    }
                    // 链接 关联单号
                    var associatedTrackingNumberLabelList = pageItems.Where(x => x.AssociatedTrackingNumberFkDisplayName != null).Select(x => x.AssociatedTrackingNumberFkDisplayName).Distinct().ToList();
                    if (associatedTrackingNumberLabelList.Any()) {
                        var associatedTrackingNumberLinkMap = _nboundmanagementRep.Context.Queryable<Commodityinformation>().Where(u => associatedTrackingNumberLabelList.Contains($"{u.ItemName}")).ToList().ToDictionary(u => $"{u.ItemName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.AssociatedTrackingNumber = associatedTrackingNumberLinkMap.GetValueOrDefault(e.AssociatedTrackingNumberFkDisplayName ?? "");
                            if (e.AssociatedTrackingNumber == null) e.Error = "关联单号链接失败";
                        });
                    }
                    // 链接 供应商
                    var vendorIdLabelList = pageItems.Where(x => x.vendorFkDisplayName != null).Select(x => x.vendorFkDisplayName).Distinct().ToList();
                    if (vendorIdLabelList.Any()) {
                        var vendorIdLinkMap = _nboundmanagementRep.Context.Queryable<Vendor>().Where(u => vendorIdLabelList.Contains($"{u.VendorName}")).ToList().ToDictionary(u => $"{u.VendorName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.vendorId = vendorIdLinkMap.GetValueOrDefault(e.vendorFkDisplayName ?? "");
                            if (e.vendorId == null) e.Error = "供应商链接失败";
                        });
                    }
                    // 链接 经办人
                    var attnLabelList = pageItems.Where(x => x.AttnFkDisplayName != null).Select(x => x.AttnFkDisplayName).Distinct().ToList();
                    if (attnLabelList.Any()) {
                        var attnLinkMap = _nboundmanagementRep.Context.Queryable<UserManagement>().Where(u => attnLabelList.Contains($"{u.UserName}")).ToList().ToDictionary(u => $"{u.UserName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.Attn = attnLinkMap.GetValueOrDefault(e.AttnFkDisplayName ?? "");
                            if (e.Attn == null) e.Error = "经办人链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<Nboundmanagement>>();
                    
                    var storageable = _nboundmanagementRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.InboundOrderNumber?.Length > 50, "入库单号长度不能超过50个字符")
                        .SplitError(it => it.Item.Buddies?.Length > 32, "联系人长度不能超过32个字符")
                        .SplitError(it => it.Item.Contact?.Length > 32, "联系方式长度不能超过32个字符")
                        .SplitError(it => it.Item.Remark?.Length > 32, "备注长度不能超过32个字符")
                        .SplitError(it => it.Item.UploadAttachments?.Length > 1000, "上传附件长度不能超过1000个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
